<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="treeData" :props="{label:'name'}" default-expand-all :expand-on-click-node="false">
        <!-- 作用域插槽 -->
        <template #default="{data}">
          <el-row type="flex" justify="space-between" :style="{width: '100%'}">
            <div>{{ data.name }}</div>
            <el-row type="flex" justify="space-between" :style="{width: '150px'}">
              <span>{{ data.managerName }}</span>
              <!-- $event 事件对象，灵活控制实参怎么传 -->
              <el-dropdown @command="onOperation($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </el-row>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- :visible @update:visible -->
    <!-- 监听@update:visible事件，将子组件传出来的值赋值给visible  -->
    <AddDep ref="addDep" :visible.sync="visible" :current-id="currentId" @refresh="loadData" />
  </div>
</template>
<script>
import { delDepartmentAPI, getDepartmentAPI } from '@/api/department'
import { arrayToTree } from '@/utils'
import AddDep from './add-dept.vue'

// 掌握tree组件的二个属性
// 1、data
// 2、props
// 3、事件
export default {
  name: 'Department',
  components: {
    AddDep
  },
  data() {
    return {
      currentId: 0,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      visible: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const res = await getDepartmentAPI()
      this.treeData = arrayToTree(res)
    },
    async onOperation(command, id) {
      if (command === 'add') {
        this.visible = true
        this.currentId = id
      } else if (command === 'edit') {
        // $refs可以拿到组件的实例对象，并且可以调用组件的方法
        await this.$refs.addDep.getDepDetail(id)
        this.visible = true
      } else if (command === 'del') {
        try {
          // 二次确认
          // 关闭国际化英文
          await this.$confirm('是否确认删除', '温馨提示')
          await delDepartmentAPI(id)
          this.$message.success('删除成功')
          // 刷新
          this.loadData()
        } catch (error) {
          console.log(error)
        }
      }
    }
  }

}
</script>
<style scoped>
.container {
  padding: 40px 140px;
  background-color: white;
  margin: 20px;
}
</style>
